<template>
  <view class="position-container">
    <!-- 顶部搜索区域 -->
    <CustomHeader ref="customHeader"></CustomHeader>
    <view class="top-box">
      <!-- 搜索栏 -->
      <view class="search-bar">
        <view class="search-wrapper">
          <view class="search-input-section">
            <view class="search-icon-wrapper">
              <image
                src="/static/images/candidate/search.png"
                class="search-icon"
              ></image>
            </view>
            <view class="split-line">
              <text class="split-text">|</text>
            </view>
            <view class="search-input-wrapper">
              <input
                type="text"
                v-model="searchKeyword"
                placeholder="请输入职位名称"
                placeholder-class="placeholder"
                class="search-input"
                @input="onSearchInput"
                @confirm="doSearch"
              />
            </view>
          </view>
        </view>

        <view class="search-btn" @click="doSearch">
          <text class="search-btn-text">搜索</text>
        </view>
      </view>

      <!-- 求职期望tabs -->
      <view class="expectation-tabs">
        <scroll-view
          scroll-x="true"
          class="tabs-scroll"
          show-scrollbar="false"
          :scroll-with-animation="true"
          enhanced
          :refresher-enabled="false"
        >
          <view
            v-for="(tab, index) in expectationTabs"
            :key="index"
            class="tab-item"
            :class="{ 'tab-active': selectedTabIndex === index }"
            @click="selectTab(index)"
          >
            <text
              class="tab-text"
              :class="{ 'tab-text-active': selectedTabIndex === index }"
            >
              {{ tab.name }}
            </text>
          </view>
        </scroll-view>
      </view>

      <!-- 筛选条件 -->
      <view class="filter-section">
        <view class="filter-left">
          <text class="filter-text">综合</text>
        </view>
        <view class="filter-right" @click="goToAreaSelect">
          <text class="filter-text">{{ selectedArea || "重庆" }}</text>
          <image
            src="/static/icons/hr/option-down-icon.png"
            class="filter-arrow"
          ></image>
        </view>
      </view>
    </view>

    <!-- 职位列表 -->
    <view class="content-section">
      <!-- 空状态 -->
      <view v-if="jobList.length === 0 && !loading" class="empty-state">
        <image
          src="/static/images/candidate/empty.png"
          class="empty-image"
        ></image>
        <text class="empty-text">暂时没有合适的职位~</text>
      </view>

      <!-- 职位列表 -->
      <scroll-view
        v-else
        class="job-list"
        scroll-y
        @scrolltolower="onScrollToLower"
        lower-threshold="50"
        :style="{ height: scrollHeight + 'px' }"
      >
        <view class="job-list-content">
          <!-- 加载中提示 -->
          <view v-if="loading && jobList.length === 0" class="loading-state">
            <text class="loading-text">加载中...</text>
          </view>

          <!-- 职位列表项 -->
          <view
            v-for="job in jobList"
            :key="job.jobId"
            class="job-item"
            @click="goToJobDetail(job.jobId)"
          >
            <view class="job-header">
              <text class="job-name">{{ job.jobName }}</text>
              <text class="job-salary">{{ formatSalary(job) }}</text>
            </view>

            <!-- 企业信息 -->
            <view class="company-info">
              <text class="company-name">{{
                job.companyName
              }}</text>
              <text class="separator">·</text>
              <text class="company-detail">{{
                job.financStage
              }}</text>
              <text class="separator">·</text>
              <text class="company-detail">{{
                formatPeopleSize(job.peopleSize)
              }}</text>
            </view>

            <!-- 岗位性质 -->
            <view class="job-nature">
              <text class="nature-tag" v-if="job.edu">{{ job.edu }}</text>
              <text class="nature-tag" v-if="job.expYears">{{
                job.expYears
              }}</text>
              <text class="nature-tag" v-if="job.monthlySalary"
                >{{ job.monthlySalary }}薪</text
              >
            </view>

            <!-- 标签 -->
            <view class="job-tags" v-if="job.tags">
              <text
                class="job-tag"
                v-for="tag in getTopTags(job.tags, 5)"
                :key="tag"
                >{{ tag }}</text
              >
            </view>

            <!-- HR信息和地址 -->
            <view class="job-footer">
              <view class="hr-info">
                <image
                  :src="job.face || '/static/images/avatar.png'"
                  class="hr-avatar"
                ></image>
                <view class="hr-text">
                  <text class="hr-name">{{ job.name || "HR" }}</text>
                  <text class="hr-position"
                    >· {{ job.position || "" }}</text
                  >
                </view>
              </view>
              <text class="job-city">{{ job.city }}</text>
            </view>
          </view>

          <!-- 加载更多 -->
          <view v-if="loadingMore" class="load-more">
            <text class="load-more-text">加载中...</text>
          </view>

          <!-- 没有更多数据 -->
          <view v-else-if="!hasMore && jobList.length > 0" class="no-more">
            <text class="no-more-text">已经到底了</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 底部tabbar -->
    <CustomTabBar :currentIndex="0" />
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from "vue";
import CustomTabBar from "@/components/CustomTabBar.vue";
import CustomHeader from "@/components/CustomHeader.vue";
import { searchJobsApi, getMyWorkExpectApi } from "@/api/position.js";
import { getDictionary } from "@/api/resume.js";
import { companySizeCacheManager } from "@/utils/cache.js";

// 响应式数据
const searchKeyword = ref("");
const selectedTabIndex = ref(0);
const selectedArea = ref("重庆");
const scrollHeight = ref(500);
const jobList = ref([]); // 职位列表
const navHeight = ref(44); // 默认导航栏高度
const customHeader = ref(null);

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const loading = ref(false);
const loadingMore = ref(false);

// 求职期望tabs（初始值）
const expectationTabs = ref([
  { id: "", name: "全部", city: "", beginSalary: null, endSalary: null },
  { id: "1", name: "Java", city: "", beginSalary: null, endSalary: null },
  { id: "2", name: "C++", city: "", beginSalary: null, endSalary: null },
  { id: "3", name: "Python", city: "", beginSalary: null, endSalary: null },
  { id: "4", name: "前端", city: "", beginSalary: null, endSalary: null },
  { id: "5", name: "UI设计", city: "", beginSalary: null, endSalary: null },
]);

// 存储完整的求职期望数据
const workExpectList = ref([]);

// 获取用户求职期望
const loadWorkExpect = async () => {
  try {
    const res = await getMyWorkExpectApi();
    console.log("用户求职期望:", res);

    if (res && Array.isArray(res)) {
      // 保存完整的求职期望数据
      workExpectList.value = res;

      // 构造新的tabs数据，包含"全部"选项和从接口获取的所有求职期望
      const newTabs = [
        { id: "", name: "全部", city: "", beginSalary: null, endSalary: null },
      ];

      // 遍历接口返回的数据，每个求职期望都作为一个tab
      res.forEach((item, index) => {
        newTabs.push({
          id: item.id,
          name: item.jobName,
          city: item.city,
          beginSalary: item.beginSalary,
          endSalary: item.endSalary,
        });
      });

      // 更新tabs数据
      expectationTabs.value = newTabs;
      console.log("更新后的tabs:", expectationTabs.value);
    }
  } catch (error) {
    console.error("获取用户求职期望失败:", error);
    // 如果获取失败，保持原来的默认tabs
  }
};

// 页面加载
onMounted(() => {
  // 监听城市选择事件
  uni.$on("citySelected", (data) => {
    console.log("接收到选择的城市:", data);
    if (data && data.city) {
      selectedArea.value = data.city;
      // 重新加载数据
      doSearch();
    }
  });

  nextTick(() => {
    calculateScrollHeight();
    // 获取公司规模数据
    loadCompanySizeData();
    // 获取用户求职期望
    loadWorkExpect().then(() => {
      // 初始化加载职位列表
      loadJobList(true);
    });
  });
});

// 页面卸载时移除事件监听
onUnmounted(() => {
  uni.$off("citySelected");
});

// 计算滚动区域高度
const calculateScrollHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    console.log("系统信息:", systemInfo);

    // 计算可用高度：总高度 - 顶部搜索区域 - tabbar高度 - 安全区域
    const topSectionHeight = uni.upx2px(260); // 搜索栏 + tabs + 筛选条件的大概高度
    const tabbarHeight = uni.upx2px(98); // tabbar高度

    // 添加安全区域底部高度
    const safeAreaBottom = systemInfo.safeAreaInsets?.bottom || 0;

    let availableHeight =
      systemInfo.windowHeight -
      topSectionHeight -
      tabbarHeight -
      safeAreaBottom;

    // 确保最小高度
    availableHeight = Math.max(availableHeight, 300);

    scrollHeight.value = availableHeight;
    console.log(
      "计算的scroll-view高度:",
      scrollHeight.value,
      "原始窗口高度:",
      systemInfo.windowHeight
    );
  } catch (error) {
    console.error("计算滚动高度失败:", error);
    // 设置一个默认高度
    scrollHeight.value = 500;
  }
};

// 搜索输入
const onSearchInput = (e) => {
  searchKeyword.value = e.detail.value;
};

// 执行搜索
const doSearch = () => {
  console.log("搜索关键词:", searchKeyword.value);
  // 重置分页参数并重新加载
  currentPage.value = 1;
  jobList.value = [];
  hasMore.value = true;
  loadJobList(true);
};

// 选择tab
const selectTab = (index) => {
  if (selectedTabIndex.value === index) return;

  selectedTabIndex.value = index;
  const selectedTab = expectationTabs.value[index];
  console.log("选择的tab:", selectedTab.name);

  // 如果选择了具体的求职期望tab，更新城市选择器的显示
  if (selectedTab.city) {
    selectedArea.value = selectedTab.city;
  }

  // 重置分页参数并重新加载
  currentPage.value = 1;
  jobList.value = [];
  hasMore.value = true;
  loadJobList(true);
};

// 跳转到区域选择
const goToAreaSelect = () => {
  console.log("跳转到区域选择页面");
  // 跳转到城市选择页面
  uni.navigateTo({
    url: "/pages/company/citySelector",
    events: {
      // 监听从选择页面返回的数据
      citySelected: function (data) {
        console.log("接收到选择的城市:", data);
        if (data && data.name) {
          selectedArea.value = data.name;
          // 重新加载数据
          doSearch();
        }
      },
    },
  });
};

// 加载职位列表
const loadJobList = async (isRefresh = false) => {
  console.log(
    "获取职位列表 - isRefresh:",
    isRefresh,
    "currentPage:",
    currentPage.value
  );

  if (loading.value && !isRefresh) {
    console.log("正在加载中，跳过");
    return;
  }
  if (loadingMore.value && isRefresh) {
    console.log("正在加载更多，跳过刷新");
    return;
  }

  try {
    if (isRefresh) {
      currentPage.value = 1;
      loading.value = true;
      jobList.value = []; // 清空列表
      console.log("刷新模式 - 清空列表，重置页码");
    } else {
      if (!hasMore.value) {
        console.log("无更多数据可加载");
        return;
      }
      loadingMore.value = true;
      console.log("加载更多模式 - 页码:", currentPage.value);
    }

    // 构造请求参数 - 只包含有效值
    const selectedTab = expectationTabs.value[selectedTabIndex.value];
    const params = {
      pageNo: isRefresh ? 1 : currentPage.value,
      pageSize: pageSize.value,
    };

    // 只有当值有效时才添加到参数中
    if (searchKeyword.value) {
      params.jobName = searchKeyword.value;
    }

    if (selectedTab.name !== "全部" && selectedTab.name) {
      params.jobType = selectedTab.name;
    }

    // 使用tab对应的city，如果没有则使用selectedArea
    const cityToUse = selectedTab.city || selectedArea.value;
    params.city = cityToUse;

    // 如果tab有薪资范围，则添加到参数中
    if (selectedTab.beginSalary !== null) {
      params.beginSalary = selectedTab.beginSalary;
    }
    if (selectedTab.endSalary !== null) {
      params.endSalary = selectedTab.endSalary;
    }

    console.log("请求参数:", params);

    const res = await searchJobsApi(params);
    console.log("职位列表响应:", res);

    if (res) {
      // 更新分页信息
      const totalPages = res.totalPages || 0;

      if (isRefresh) {
        jobList.value = res.list || [];
        currentPage.value = 1;
        console.log("刷新完成 - 当前列表长度:", jobList.value.length);
      } else {
        jobList.value.push(...(res.list || []));
        console.log("加载更多完成 - 当前列表长度:", jobList.value.length);
      }

      // 判断是否还有更多数据
      hasMore.value = currentPage.value < totalPages;
      console.log(
        "分页状态 - hasMore:",
        hasMore.value,
        "currentPage:",
        currentPage.value,
        "totalPages:",
        totalPages
      );
    }
  } catch (error) {
    console.error("获取职位列表失败:", error);
    uni.showToast({
      title: "获取职位列表失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
    loadingMore.value = false;
    console.log(
      "请求结束 - loading:",
      loading.value,
      "loadingMore:",
      loadingMore.value
    );
  }
};

// 滚动到底部加载更多
const onScrollToLower = () => {
  console.log(
    "滚动到底部 - 触发加载更多 - currentPage:",
    currentPage.value,
    "hasMore:",
    hasMore.value,
    "loadingMore:",
    loadingMore.value
  );

  if (loadingMore.value || !hasMore.value) {
    console.log("已在加载中或无更多数据");
    return;
  }

  const nextPage = currentPage.value + 1;
  // 这里不需要检查totalPages，因为在loadJobList中会处理
  currentPage.value = nextPage;
  loadJobList(false);
};

// 格式化薪资显示
const formatSalary = (job) => {
  if (job.beginSalary && job.endSalary) {
    return `${job.beginSalary}-${job.endSalary}K`;
  }
  return "面议";
};

// 格式化发布时间
const formatPublishTime = (time) => {
  if (!time) return "";
  // 简单处理，实际项目中可能需要更精确的时间处理
  return time.split(" ")[0];
};

// 获取前N个标签
const getTopTags = (tags, count) => {
  if (!tags) return [];
  const tagArray = tags.split(",");
  return tagArray.slice(0, count);
};

// 格式化公司规模
const formatPeopleSize = (peopleSize) => {
  if (!peopleSize) return "";

  // 首先尝试从缓存中获取
  const cachedValue = companySizeCacheManager.getValueByDataKey(peopleSize);
  if (cachedValue !== peopleSize) {
    return cachedValue;
  }

  // 如果缓存中没有，则使用硬编码的映射（作为后备方案）
  const sizeMap = {
    counts0_50: "0-50人",
    counts50_100: "50-100人",
    counts100_500: "100-500人",
    counts500_999: "500-999人",
    counts1000_9999: "1000-9999人",
    counts10000: "10000人以上",
  };

  return sizeMap[peopleSize] || peopleSize;
};

// 获取公司规模数据
const loadCompanySizeData = async () => {
  try {
    // 检查缓存中是否有数据
    const cachedData = companySizeCacheManager.getData();
    if (cachedData) {
      console.log("使用缓存的公司规模数据");
      return;
    }

    // 从接口获取数据
    const res = await getDictionary("staff_size");
    console.log("获取到公司规模数据:", res);

    if (res && Array.isArray(res)) {
      // 保存到缓存
      companySizeCacheManager.setData(res);
    }
  } catch (error) {
    console.error("获取公司规模数据失败:", error);
  }
};

// 跳转到职位详情
const goToJobDetail = (jobId) => {
  console.log("跳转到职位详情，jobId:", );
  uni.navigateTo({
    url: `/pages/candidate/position/positionDetail?jobId=${jobId}`,
  });
};

// 重新计算高度（提供给外部调用）
const recalculateHeight = () => {
  nextTick(() => {
    calculateScrollHeight();
  });
};

// 暴露方法给父组件
defineExpose({
  recalculateHeight,
});
</script>

<style lang="less" scoped>
.position-container {
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding-bottom: 98rpx; /* 给tabbar留空间 */
  overflow: hidden;
}

/* 顶部搜索区域 */
.top-box {
  background-color: #ffffff;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

/* 搜索栏 */
.search-bar {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.search-wrapper {
  flex: 1;
  height: 80rpx;
  background-color: #f8f8f8;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}

.search-input-section {
  flex: 1;
  display: flex;
  align-items: center;
  height: 100%;
}

.search-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
}

.split-line {
  padding: 0 15rpx;
}

.split-text {
  color: #d0d0d0;
  font-size: 28rpx;
}

.search-input-wrapper {
  flex: 1;
  padding-right: 20rpx;
}

.search-input {
  width: 100%;
  font-size: 28rpx;
  color: #333333;
}

.placeholder {
  color: #b0b0b0;
}

.search-btn {
  width: 120rpx;
  height: 80rpx;
  background-color: #00bdb4;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-btn-text {
  color: #ffffff;
  font-size: 28rpx;
  font-weight: 500;
}

/* 求职期望tabs */
.expectation-tabs {
  margin-bottom: 20rpx;
}

.tabs-scroll {
  white-space: nowrap;
  /* 隐藏滚动条 - 多种方法确保兼容性 */
  &::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
    height: 0 !important;
    background: transparent !important;
  }

  scrollbar-width: none !important; /* Firefox */
  -ms-overflow-style: none !important; /* IE 10+ */

  /* 针对不同平台的特殊处理 */
  &::-webkit-scrollbar-thumb {
    background: transparent !important;
  }

  &::-webkit-scrollbar-track {
    background: transparent !important;
  }
}

.tab-item {
  display: inline-block;
  padding: 16rpx 32rpx;
  margin-right: 20rpx;
  background-color: #f8f8f8;
  border-radius: 30rpx;
  transition: all 0.3s ease;
}

.tab-active {
  background-color: #00bdb4;
}

.tab-text {
  font-size: 26rpx;
  color: #666666;
  white-space: nowrap;
}

.tab-text-active {
  color: #ffffff;
  font-weight: 500;
}

/* 筛选条件 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.filter-left,
.filter-right {
  display: flex;
  align-items: center;
}

.filter-text {
  font-size: 28rpx;
  color: #333333;
}

.filter-right {
  cursor: pointer;
}

.filter-arrow {
  width: 24rpx;
  height: 24rpx;
  margin-left: 8rpx;
}

/* 内容区域 */
.content-section {
  flex: 1;
  background-color: #f8f8f8;
  overflow: hidden;
  position: relative;
}

/* 职位列表 */
.job-list {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  /* 隐藏滚动条 - 多种方法确保兼容性 */
  &::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
    height: 0 !important;
    background: transparent !important;
  }

  scrollbar-width: none !important; /* Firefox */
  -ms-overflow-style: none !important; /* IE 10+ */

  /* 针对不同平台的特殊处理 */
  &::-webkit-scrollbar-thumb {
    background: transparent !important;
  }

  &::-webkit-scrollbar-track {
    background: transparent !important;
  }
}

.job-list-content {
  padding: 20rpx;
}

.job-item {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.job-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  flex: 1;
  margin-right: 20rpx;
}

.job-salary {
  font-size: 30rpx;
  font-weight: 600;
  color: #00bdb4;
}

.company-info {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.company-name {
  font-size: 26rpx;
  color: #666666;
  margin-right: 8rpx;
}

.separator {
  font-size: 26rpx;
  color: #999999;
  margin: 0 8rpx;
}

.company-detail {
  font-size: 26rpx;
  color: #999999;
}

.job-nature {
  display: flex;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.nature-tag {
  font-size: 24rpx;
  color: #666666;
  background-color: #f5f5f5;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
}

.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.job-tag {
  font-size: 24rpx;
  color: #999999;
  background-color: #f5f5f5;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
}

.job-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hr-info {
  display: flex;
  align-items: center;
}

.hr-avatar {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  margin-right: 12rpx;
}

.hr-text {
  display: flex;
  align-items: center;
}

.hr-name {
  font-size: 26rpx;
  color: #999999;
}

.hr-position {
  font-size: 26rpx;
  color: #999999;
  margin-left: 4rpx;
}

.job-city {
  font-size: 26rpx;
  color: #999999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 100rpx 0;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

/* 加载状态 */
.loading-state,
.load-more,
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
}

.loading-text,
.load-more-text,
.no-more-text {
  font-size: 28rpx;
  color: #999999;
}

/* 全局滚动条隐藏 */
::-webkit-scrollbar {
  display: none !important;
  width: 0 !important;
  height: 0 !important;
  background: transparent !important;
}

::-webkit-scrollbar-thumb {
  background: transparent !important;
}

::-webkit-scrollbar-track {
  background: transparent !important;
}

/* 针对特定平台的滚动条隐藏 */
scroll-view ::-webkit-scrollbar {
  display: none !important;
  width: 0 !important;
  height: 0 !important;
}
</style>